package com.nbclass.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbclass.model.BizCategory;
import com.nbclass.service.BizCategoryService;
import com.nbclass.util.PageUtil;
import com.nbclass.util.ResultUtil;
import com.nbclass.vo.base.PageResultVo;
import com.nbclass.vo.base.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("category")
public class CategoryController {
    @Autowired
    private BizCategoryService categoryService;

    @PostMapping("list")
    @ResponseBody
    public PageResultVo loadCategory(BizCategory bizCategory, Integer limit, Integer offset){
        PageHelper.startPage(PageUtil.getPageNo(limit, offset),limit);
        List<BizCategory> categoryList= categoryService.selectCategories(bizCategory);
        PageInfo<BizCategory> pages = new PageInfo<>(categoryList);
        return ResultUtil.table(categoryList,pages.getTotal());
    }
    @PostMapping("/add")
    @ResponseBody
    public ResponseVo add(BizCategory bizCategory){
        Date date = new Date();
        bizCategory.setCreateTime(date);
        bizCategory.setUpdateTime(date);
        int i = categoryService.insert(bizCategory);
        if(i>0){
            return ResultUtil.success("新增分类成功");
        }else{
            return ResultUtil.error("新增分类失败");
        }
    }

    @GetMapping("/edit")
    public String edit(Model model, Integer id){
        BizCategory bizCategory = categoryService.selectByPrimaryKey(id);
        model.addAttribute("category", bizCategory);
        return "category/detail";
    }

    @PostMapping("/edit")
    @ResponseBody
    public ResponseVo edit(BizCategory bizCategory){
        bizCategory.setUpdateTime(new Date());
        int i = categoryService.updateNotNull(bizCategory);
        if(i>0){
            return ResultUtil.success("编辑分类成功");
        }else{
            return ResultUtil.error("编辑分类失败");
        }
    }
    @PostMapping("/delete")
    @ResponseBody
    public ResponseVo delete(Integer id){
        int i = categoryService.delete(id);
        if(i>0){
            return ResultUtil.success("删除分类成功");
        }else{
            return ResultUtil.error("删除分类失败");
        }
    }
    @PostMapping("/batch/delete")
    @ResponseBody
    public ResponseVo deleteBatch(@RequestParam("ids[]") Integer[]ids){
        int i = categoryService.deleteBatch(ids);
        if(i>0){
            return ResultUtil.success("删除分类成功");
        }else{
            return ResultUtil.error("删除分类失败");
        }
    }

}
